package com.powergisol.gis.timer;

import com.powergisol.gis.dao.BoreholeQueryMapper;
import com.powergisol.gis.dao.TabYcMapper;
import com.powergisol.gis.entity.TabArea;
import com.powergisol.gis.entity.TabTask;
import com.powergisol.gis.entity.TabYc;
import com.powergisol.gis.service.TabTaskService;
import com.powergisol.gis.service.TabYcService;
import com.powergisol.gis.vo.DrillModel;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Description:任务列表
 */
@Component
public class TaskProgressTimer {

    @Autowired
    private TabTaskService tabTaskService;

    @Resource
    private CacheManager cacheManager;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private TabYcMapper tabYcMapper;

    @Autowired
    private BoreholeQueryMapper boreholeQueryMapper;

    @Value("${progress-url}")
    private String progressUrl;

    @Value("${result-url}")
    private String resultUrl;

    //第一次延迟1秒后执行，之后按fixedRate的规则每5秒执行一次
    @Scheduled(initialDelay = 1000, fixedRate = 2000)
    public void getYcProgress(){
        //岩层任务
        List<TabTask> listYcTask = tabTaskService.getByState(0,1);
        for (TabTask task:listYcTask) {
            //调用接口
            try {
                ObjectMapper mapper = new ObjectMapper();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                DrillModel drillModel = new DrillModel();
                drillModel.setRequestGuid(task.getUuid());
                HttpEntity<String> request = new HttpEntity<>(mapper.writeValueAsString(drillModel), headers);
                ResponseEntity<String> responseEntity = restTemplate.postForEntity(progressUrl, request, String.class);
                String ycProgress = responseEntity.getBody();
                Double progress = Double.parseDouble(ycProgress);

                //如果结果返回100则查看结果
                if(progress == 100 ){
                    responseEntity = restTemplate.postForEntity(resultUrl, request, String.class);
                    String body = responseEntity.getBody();
                    Map<String, Object> bodyMap =  mapper.readValue(body, new TypeReference<Map<String, Object>>() {});
                    if(("N").equals(bodyMap.get("Status"))){
                        System.out.println("生成岩层失败="+bodyMap.get("Content"));
                        TabYc tabYc = tabYcMapper.selectYcByUuid(task.getUuid());
                        tabYc.setState(-1);
                        tabYcMapper.upTabYc(tabYc);

                        task.setTaskState(2);
                        task.setRemark("生成岩层失败:"+bodyMap.get("Content").toString());
                        task.setUpTime(new Date());
                        progress = 0d;
                    }else{
                        String userDir = System.getProperty("user.dir");
                        String fileWallUrl = userDir+File.separator +"wall"+File.separator+task.getUuid()+".json";
                        String filePlaneUrl = userDir+File.separator +"plane"+File.separator+task.getUuid()+".json";
                        TabYc tabYc = tabYcMapper.selectYcByUuid(task.getUuid());
                        tabYc.setWall(fileWallUrl);
                        tabYc.setPlane(filePlaneUrl);
                        tabYc.setState(1);
                        tabYcMapper.upTabYc(tabYc);

                        task.setTaskState(1);
                        task.setUpTime(new Date());
                    }
                }
                task.setProgress(progress);
                tabTaskService.upTask(task);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //缓存读取进度
        List<TabTask> listTask = tabTaskService.getByState(0,2);
        for (TabTask task:listTask) {
            //查询缓存
            Cache cache = cacheManager.getCache("cache-data");
            if(null != cache.get(task.getUuid()+"progress")){
                Double progress = cache.get(task.getUuid()+"progress",Double.class);
                task.setProgress(progress);
                tabTaskService.upTask(task);
            }
        }
    }
    //第一次延迟1秒后执行，之后按fixedRate的规则每5秒执行一次
    @Scheduled(initialDelay = 1000, fixedRate = 1000)
    public void upZK(){
        List<Object> list = boreholeQueryMapper.getUpZk();
        for (Object o:list){
            Map<String, Object> m = (Map<String, Object>) o;
            String point = "POINT("+((Map<String, Object>) o).get("zkx")+" "+((Map<String, Object>) o).get("zky")+")";
            if(StringUtils.isBlank(point)) continue;
            TabArea tabArea = boreholeQueryMapper.getAreaByPoint(point);
            boreholeQueryMapper.upZk(null == tabArea?null:tabArea.getCode(),m.get("id").toString());
        }

    }
}
